'use client';

import type { FlowVO } from '@/app/api/flows/route';
import type { PaginatedResult } from '@/libs/pagination';
import {
  Button,
  Select,
  Upload,
  Spin,
  Empty,
  Image,
  Toast,
  Form,
} from '@douyinfe/semi-ui';
import { Icon } from '@iconify/react';
import { useState, useCallback, useRef, useEffect, useContext } from 'react';
import useSWR from 'swr';
import { clientFetch } from '@/utils/request';
import type { ApiResponse } from '@/libs/apiResponse';
import { useFlow } from '@/hooks/useFlow';
import { v4 as uuidv4 } from 'uuid';
import { DocxContext } from '@/contexts/DocxContext';

interface Props {
  onChange?: (
    value: string | number | any[] | Record<string, any> | undefined
  ) => void;
  getAllFlows?: (flows: FlowVO[]) => void;
  selectedFlow: string | number;
}

export default function FlowSelectCard({
  onChange,
  selectedFlow,
  getAllFlows,
}: Props) {
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize] = useState<number>(20);
  const [allFlows, setAllFlows] = useState<FlowVO[]>([]);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const { docxRef } = useContext(DocxContext);

  const observerRef = useRef<HTMLDivElement>(null);
  const { analyseImage, isAnalyzing } = useFlow();

  useEffect(() => {
    if (getAllFlows) {
      getAllFlows(allFlows);
    }
  }, [allFlows]);

  const params = new URLSearchParams({
    page: `${currentPage}`,
    pageSize: `${pageSize}`,
  });

  const fetcher = async () => {
    const res = await clientFetch.get<PaginatedResult<FlowVO>>(
      `/api/flows?${params.toString()}`
    );

    if (res.code !== 200) {
      throw new Error(res.message || '请求失败');
    }

    return res.data;
  };

  const { data, isLoading, error } = useSWR(
    `/api/flows?${params.toString()}`,
    fetcher
  );

  // 处理数据更新
  useEffect(() => {
    if (data?.data) {
      if (currentPage === 1) {
        setAllFlows(data.data);
      } else {
        setAllFlows((prev) => [...prev, ...data.data]);
      }

      // 检查是否还有更多数据
      setHasMore(
        data.data.length === pageSize &&
          currentPage < (data.pagination.total || 0)
      );
    }
  }, [data, currentPage, pageSize]);

  // 无限滚动逻辑
  const loadMore = useCallback(() => {
    if (!isLoading && hasMore) {
      setCurrentPage((prev) => prev + 1);
    }
  }, [isLoading, hasMore]);

  // Intersection Observer
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          loadMore();
        }
      },
      { threshold: 0.1 }
    );

    if (observerRef.current) {
      observer.observe(observerRef.current);
    }

    return () => observer.disconnect();
  }, [loadMore]);

  const handleFlowChange = (
    value: string | number | any[] | Record<string, any> | undefined
  ) => {
    if (onChange) {
      onChange(value);
      const selectedFlow = allFlows.find((flow) => flow._id === value);
      docxRef.current = {
        ...docxRef.current,
        flowImage: {
          image_path: selectedFlow?.imageUrl,
        },
      };
    }
  };

  const handleUploadSuccess = async (responseBody: ApiResponse<any>) => {
    try {
      const url = responseBody.data.url;
      const res = await analyseImage(url);
      const id = uuidv4();

      setAllFlows((prev) => [
        ...prev,
        {
          _id: `custom-${id}`,
          aiAnalysisText: res || '',
          code: `custom-${id}`,
          name: `自定义工艺-${id}`,
          imageUrl: url,
        },
      ]);

      // 通知选择变更
      handleFlowChange(`custom-${id}`);
    } catch (error) {
      console.error(error);
      Toast.error('AI 分析失败了');
    }
  };

  return (
    <div className="group rounded-xl border border-gray-200/80 bg-white p-6 shadow-sm transition-all duration-300 hover:border-gray-300/80 hover:shadow-md">
      {/* 标题部分 */}
      <div className="mb-6">
        <h3 className="flex items-center text-lg font-semibold text-gray-800">
          <div className="mr-3 h-6 w-1.5 rounded-full bg-gradient-to-b from-yellow-400 to-yellow-600"></div>
          <span>工艺流程选择</span>
          <div className="ml-2 rounded-full bg-gray-100 px-2 py-1 text-xs text-gray-600">
            {allFlows.length} 项
          </div>
        </h3>
        <p className="mt-1 text-sm text-gray-500">
          选择现有工艺流程或上传自定义配置
        </p>
      </div>

      {/* 主要内容区域 */}
      <div className="space-y-4">
        {/* 选择器区域 */}
        <div className="relative">
          <Select
            placeholder="请选择工艺流程..."
            value={selectedFlow}
            onChange={handleFlowChange}
            className="w-full"
            size="large"
            filter
            remote
            emptyContent={
              error ? (
                <div className="flex flex-col items-center py-6 text-gray-500">
                  <Icon icon="lucide:wifi-off" className="mb-2 h-8 w-8" />
                  <span>加载失败，请重试</span>
                </div>
              ) : allFlows.length === 0 && !isLoading ? (
                <Empty
                  image={
                    <Icon
                      icon="lucide:inbox"
                      className="h-12 w-12 text-gray-400"
                    />
                  }
                  title="暂无工艺流程"
                  description="请先创建工艺流程或上传配置文件"
                />
              ) : null
            }
            dropdownClassName="max-h-80 overflow-y-auto"
          >
            {allFlows.map((flow, index) => (
              <Form.Select.Option
                key={`${flow.code}-${index}`}
                value={flow._id}
                data-ai={flow.aiAnalysisText}
                className="group/option"
              >
                <div className="flex items-center justify-between">
                  <div className="flex-1">
                    <div className="font-medium text-gray-800 group-hover/option:text-blue-600">
                      {flow.name}
                    </div>
                  </div>
                  <div className="ml-2 text-xs text-gray-400">{flow.code}</div>
                </div>
              </Form.Select.Option>
            ))}

            {/* 加载更多指示器 */}
            {hasMore && (
              <div ref={observerRef} className="flex justify-center py-3">
                {isLoading ? (
                  <div className="flex items-center text-gray-500">
                    <Spin size="small" />
                    <span className="ml-2 text-sm">加载中...</span>
                  </div>
                ) : (
                  <div className="text-xs text-gray-400">滚动加载更多</div>
                )}
              </div>
            )}
          </Select>
        </div>

        {/* 上传区域 */}
        <div className="flex items-center space-x-3">
          <div className="h-px flex-1 bg-gradient-to-r from-transparent via-gray-200 to-transparent"></div>
          <span className="text-xs text-gray-400">或</span>
          <div className="h-px flex-1 bg-gradient-to-r from-transparent via-gray-200 to-transparent"></div>
        </div>

        <Upload
          action="/api/upload"
          accept=".png,.jpg,.jpeg"
          name="file"
          onSuccess={handleUploadSuccess}
          showUploadList={false}
          className="w-full"
        >
          <Button
            size="large"
            type="tertiary"
            loading={isAnalyzing}
            icon={<Icon icon="lucide:upload" className="h-4 w-4" />}
            className="group/upload w-full border-2 border-dashed border-gray-200 bg-gray-50/50 transition-all duration-200 hover:border-blue-300 hover:bg-blue-50/50"
          >
            <span className="text-gray-600 group-hover/upload:text-blue-600">
              {isAnalyzing ? 'AI 分析中' : '上传自定义工艺配置'}
            </span>
          </Button>
        </Upload>

        {/* 提示信息 */}
        <div className="rounded-lg bg-blue-50/50 p-3 text-sm text-blue-600">
          <div className="flex items-start space-x-2">
            <Icon icon="lucide:info" className="mt-0.5 h-4 w-4 flex-shrink-0" />
            <div>
              <div className="font-medium">支持的文件格式</div>
              <div className="mt-1 text-blue-500">
                PNG、JPG、JPEG 格式的工艺图
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 选中状态显示 */}
      {selectedFlow && (
        <div className="mt-4 rounded-lg border border-green-200 bg-green-50/50 p-4">
          <div className="flex items-center space-x-3">
            <Icon
              icon="lucide:check-circle"
              className="h-5 w-5 flex-shrink-0 text-green-600"
            />

            {/* 选中流程的详细信息 */}
            <div className="flex-1">
              <div className="flex items-center space-x-3">
                {/* 选中流程的图片预览 */}
                {(() => {
                  const selectedFlowData = allFlows.find(
                    (f) => f._id === selectedFlow
                  );

                  return selectedFlowData?.imageUrl ? (
                    <div className="relative h-auto w-20 flex-shrink-0 overflow-hidden rounded-lg border-2 border-green-300">
                      <Image
                        src={selectedFlowData.imageUrl}
                        alt={selectedFlowData.name || '选中的工艺流程'}
                        className="h-full object-cover"
                      />
                    </div>
                  ) : (
                    <div className="flex h-16 w-20 flex-shrink-0 items-center justify-center rounded-lg border-2 border-green-300 bg-gradient-to-br from-green-100 to-green-200">
                      <Icon
                        icon="lucide:workflow"
                        className="h-6 w-6 text-green-600"
                      />
                    </div>
                  );
                })()}

                {/* 选中流程的文字信息 */}
                <div className="min-w-0 flex-1">
                  <div className="text-sm font-medium text-green-800">
                    已选择工艺流程
                  </div>
                  <div className="truncate text-base font-semibold text-green-900">
                    {allFlows.find((f) => f.code === selectedFlow)?.name}
                  </div>
                  <div className="mt-1 text-xs text-green-600">
                    编号: {selectedFlow}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
